﻿
$(document).ready(function () {
    AGSamples.settingsPage.initialize();
});

var AGSamples = window.AGSamples || {};

AGSamples.settingsPage = {
    appWeb: "",
    hostWeb: "",
    appWebUrl: "",
    hostWeburl: "",
    context: null,
    contextHostWeb: null,

    initialize: function () {
        $('#btnApply').click(Function.createDelegate(this, this.btnApply_click));

        this.appWebUrl = decodeURIComponent(getQuerystring("SPAppWebUrl"));
        this.hostWeburl = decodeURIComponent(getQuerystring("SPHostUrl"));

        this.context = new SP.ClientContext.get_current();
        this.contextHostWeb = new SP.AppContextSite(this.context, this.hostWeburl);

        this.appWeb = this.context.get_web();
        this.hostWeb = this.contextHostWeb.get_web();

        this.context.load(this.appWeb);
        this.context.load(this.hostWeb);

        this.context.executeQueryAsync(
                Function.createDelegate(this, this.initializeSucceeded),
                Function.createDelegate(this, this.errorHandler));
    },

    initializeSucceeded: function () {
        alert("hostWeb title = " + this.hostWeb.get_title() + "\n appWeb title = " + this.appWeb.get_title());
    },

    btnApply_click: function () {
        this.UploadMasterPageTohostWeb("DreamTheme.master");
        this.UploadTextFileTohostWeb("DreamTheme.css", "Style Library", "/Style%20Library/DreamTheme/");
        //this.UploadImageTohostWeb("Ferrari.jpg", "Style Library", "/Style%20Library/DreamTheme/");
    },

    UploadMasterPageTohostWeb: function (masterPageName) {
        var masterPageGallery;
        var masterPageListItem;
        var masterPageContents;

        var fileCreateInfo;
        var fileContent;

        $.get(this.appWebUrl + '/_catalogs/masterpage/' + masterPageName,
            Function.createDelegate(this, function (data) {
                masterPageContents = data

                masterPageGallery = this.hostWeb.get_lists().getByTitle("Master Page Gallery");

                this.context.load(masterPageGallery);
                fileCreateInfo = new SP.FileCreationInformation();
                fileCreateInfo.set_url(masterPageName);
                fileCreateInfo.set_content(new SP.Base64EncodedByteArray());
                fileCreateInfo.set_overwrite(true);

                fileContent = masterPageContents;

                for (var i = 0; i < fileContent.length; i++) {

                    fileCreateInfo.get_content().append(fileContent.charCodeAt(i));
                }

                var newFile = masterPageGallery.get_rootFolder().get_files().add(fileCreateInfo);

                this.context.load(newFile);
                masterPageListItem = newFile.get_listItemAllFields();
                masterPageListItem.set_item("ContentTypeId", "0x010105");
                masterPageListItem.set_item("UIVersion", "15");
                masterPageListItem.update();


                this.context.executeQueryAsync(
                    Function.createDelegate(this, this.masterPageUploaded),
                    Function.createDelegate(this, this.errorHandler)
                );
            }));
    },

    UploadTextFileTohostWeb: function (fileName, libraryTitle, libraryUrl) {

        $.get(this.appWebUrl + libraryUrl + fileName,
            Function.createDelegate(this, function (data) {

                var library;
                var listItem;
                var contents;
                var fileCreateInfo;
                var fileContent;

                contents = data

                library = this.hostWeb.get_lists().getByTitle(libraryTitle);

                //file.Checkout of file.delete
                this.context.load(library);
                fileCreateInfo = new SP.FileCreationInformation();
                fileCreateInfo.set_url(fileName);
                fileCreateInfo.set_content(new SP.Base64EncodedByteArray());
                fileCreateInfo.set_overwrite(true);
                fileContent = contents;

                for (var i = 0; i < fileContent.length; i++) {

                    fileCreateInfo.get_content().append(fileContent.charCodeAt(i));
                }

                var newFile = library.get_rootFolder().get_files().add(fileCreateInfo);

                this.context.load(newFile);
                listItem = newFile.get_listItemAllFields();
                listItem.update();

                this.context.executeQueryAsync(
                    Function.createDelegate(this, this.fileUploaded),
                    Function.createDelegate(this, this.errorHandler)
                );
            }));
    },
    UploadImageTohostWeb: function (fileName, libraryTitle, libraryUrl) {
        var ro;
        ro = new SP.RequestExecutor(this.hostWeburl);

        var canvas = document.createElement("canvas");
        var ctx

        var img = new Image();

        img.onload = function () {
            canvas.width = img.width;
            canvas.height = img.height;
            ctx = canvas.getContext("2d");
            ctx.drawImage(this, 0, 0);

            var dataURL = canvas.toDataURL("image/jpg");

            var body = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
            var info = {
                url: "_api/web/lists/getByTitle('" + libraryTitle + "')/RootFolder/Files/Add(url='" + fileName + "', overwrite=true)",
                method: "POST",
                binaryStringRequestBody: true,
                body: body,
                success: this.imageUploaded,
                error: this.errorHandler,
                state: "Update"
            };
            ro.executeAsync(info);

        };
        img.src = this.appWebUrl + libraryUrl + fileName;

    },

    masterPageUploaded: function () {
        alert("Masterpage uploaded!");
        this.ApplyBranding("DreamTheme.master");
    },

    ApplyBranding: function (masterPage) {

        var urlMasterPage = this.hostWeb.get_serverRelativeUrl() + "/_catalogs/masterpage/" + masterPage;

        this.hostWeb.set_masterUrl(urlMasterPage);
        this.hostWeb.update();

        this.context.executeQueryAsync(
            Function.createDelegate(this, this.brandingApplied),
            Function.createDelegate(this, this.errorHandler)
        );
    },



    fileUploaded: function () {
        alert("file uploaded!");
    },

    brandingApplied: function () {
        alert("Branding applied!");
    },
    imageUploaded: function () {
        alert("image uploaded!");
    },

    errorHandler: function (sender, args) {
        if (args.get_message != null) {
            alert("Error:" + args.get_message());
        }
        else {
            alert("Error occured");
        }
    }



}

function base64Encode(str) {
    var CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    var out = "", i = 0, len = str.length, c1, c2, c3;
    while (i < len) {
        c1 = str.charCodeAt(i++) & 0xff;
        if (i == len) {
            out += CHARS.charAt(c1 >> 2);
            out += CHARS.charAt((c1 & 0x3) << 4);
            out += "==";
            break;
        }
        c2 = str.charCodeAt(i++);
        if (i == len) {
            out += CHARS.charAt(c1 >> 2);
            out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
            out += CHARS.charAt((c2 & 0xF) << 2);
            out += "=";
            break;
        }
        c3 = str.charCodeAt(i++);
        out += CHARS.charAt(c1 >> 2);
        out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
        out += CHARS.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
        out += CHARS.charAt(c3 & 0x3F);
    }
    return out;
}




function getQuerystring(key, default_) {
    if (default_ == null) default_ = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if (qs == null)
        return default_;
    else
        return qs[1];
}


